define(['jquery','select2','text!../template/user.html','text!../template/userMsg.html','css!../css/user','common'],function($,select2,tplUser,tplMsg){
	let _user = {};
	let currentPage = 1;
	let currentStatus=2;
	var tpls = {
		'tplUser' :_.template(tplUser),
		'tplMsg' :_.template(tplMsg)
	};

	_user.show = function(){
		currentPage = 1;
		let currentAreaId = '';
		let currentAreaType = '';
		$('#contant').html(tpls.tplUser());
		setTable(0,5);
		let setting = {
	        check: {
	            enable: true,
	            chkStyle: "radio",
	            radioType: 'all',
	            //chkboxType: {"Y" : "s", "N" : "s"}
	        },
	        async: {
	            enable: true,
	            autoParam:["id", "name=n", "level=lv"],
	            otherParam:{"parentId":"320113"},
	            type: "post",
	        },
	        callback:{
	            onCheck:zTreeOnCheck,
	            onClick: function (e, treeId, treeNode, clickFlag) { 
					var zTree = $.fn.zTree.getZTreeObj("treeDemo");
					zTree.checkNode(treeNode, !treeNode.checked, true);
					zTreeOnCheck(e, treeId, treeNode);
				}
	        }
	    };
        setTree("#treeDemo",setting);

        function zTreeOnCheck(event, treeId, treeNode){
	        currentAreaId = treeNode.id;
	        currentAreaType = treeNode.type;
	        $('#areaSel').val(treeNode.name);
	        $("#areaClear").show();
	    }

	    $("#areaClear").click(function(event) {
			currentAreaId = '';
	        currentAreaType = '';
	        $(this).hide();
        	$('#areaSel').val('按管辖区域');
    		setTree("#treeDemo",setting);
		});
	    
		$("#addUser").click(function(event) {
			showInfo();
		});

		$('#areaSel').click(function(event) {
		    event.stopPropagation();
			$('.treeBox').toggle();
		});
		$('.treeBox').click(function(event) {
			event.stopPropagation();
		});

		$('body').click(function(event) {
			if($('.treeBox').is(':visible')){
				$('.treeBox').hide();
			}
		});

		$('#userSelect').click(function(event) {
			let parms = {};
			parms.userName = $('#nameSel').val();
			parms.phone = $('#nameSel').val();
			parms.role = $('#typeSel').val();
			parms.gender = $('#sexSel').val();
			parms.areaId = currentAreaId;
			parms.areaType = currentAreaType;
			currentPage = 1;
			setTable(0,5,parms);
		});
	}

	window.showInfo = function (data,type){
		let _data={};
		Ajax("/xjrest/area/area_tree?parentId=320113",treeBack,'','post');
		function treeBack(treeDatas){
			if(data){
				_data=data;
			}
			_data.tree = treeDatas;
			let _html = tpls.tplMsg({message:_data});
			layer.open({
			  type: 1,
			  title: false,
			  closeBtn: 0,
			  shadeClose: true,
			  skin: 'userOpen',
			  content: _html
			});
			$('#childPut').click(function(event) {
				event.stopPropagation();
				$('.childTree').toggle();
			});
			$('body').click(function(event) {
				$('.childTree').hide();
			});
			$('.childTree').click(function(event) {
				event.stopPropagation();
			});
			$('#userTypes').change(function(event) {
				let flag = $(this).val();
				if(flag==1){
					$('#townSelect,#villageSelect').hide();
				}else if(flag==2){
					$('#villageSelect').hide();
					$('#townSelect').show();
				}else{
					$('#villageSelect').show();
					$('#townSelect').show();
				}
			});
			let child = $('#userTown').val();
			let set = {
	            check: {
	                enable: true,
	                radioType: 'all',
	                chkboxType: {"Y" : "s", "N" : "s"}
	            },
	            callback:{
	                onCheck:childCheck
	            }
	        }
	        function childCheck(event, treeId, treeNode){
	            var v="";
		        let treeObj=$.fn.zTree.getZTreeObj('childTree');
		        nodes=treeObj.getCheckedNodes(true);
		        let newNodes = [];
		        for(var i=0;i<nodes.length;i++){
	            	if(nodes[i].name!='全选'){newNodes.push(nodes[i])}
	            }
	            for(var i=0;i<newNodes.length;i++){
	            	v+=newNodes[i].name + ",";
	            }
	            $('#childPut').attr('nodes',JSON.stringify(newNodes));
	            $('#childPut').attr('title',v);
	            $('#childPut').val(truncate(v,15));
	            if($('#childPut').val()==''){$('#childPut').val('选择社区')}
	        }
			data?setChildren('#childTree',child,set,data.village):setChildren('#childTree',child,set);
			$('#userTown').change(function(event) {
				let target = event.currentTarget;
				setChildren('#childTree',$(target).val(),set);
				$('#childPut').val('选择社区').attr('nodes','');
			});
			$('#closeInfo').click(function(event) {
				$('.layui-layer-shade').click();
			});
			$('input[type=radio][name=type]').change(function(event) {
				
				
				if($('#on').prop('checked')){
					currentStatus = 2;
				}else {
					currentStatus = 3;
				}
				$('.typeImg').toggle();
			});
			if(data){
				$('#account').attr('disabled',true);
				$('#password').attr('disabled',true);
				$("#userTypes").val(data.role);
				$("#userSex").val(data.gender);
				$('.userRow').hide();
				if(data.status==2){
					$('#on').click();
				}else if (data.status==3) {
					$('#off').click();
				}
				if(type == 'update'){
					$('#submit').val('确认修改');
					$('#resetPwd').show().click(function(event) {
						layer.confirm('确定重置密码？', {
			                btn: ['确定', '取消']
			            }, function() {
			                layer.closeAll();
			                Ajax("/xjrest/user/admin_reset_pwd?userId="+data.userId,function(data){
			                	if(data.ret.success){
			                		layer.msg('密码已重置为: 123456');
			                	}else{
			                		layer.msg(data.ret.message);
			                	}
			                });
			            }, function() {

			            });
					});
				}else{
					$('#submit').hide();
					$('.userOpen input,.userOpen select').attr('disabled',true);
				}
			}
			checkBlur('.userInfoBody');
			$('#submit').click(function(event) {
				if(checkInput('.userInfoBody')==1){
                    layer.msg('请输入完整信息');
                    return;
                }
				let parms = {};
				if($('#submit').val()=='确认修改'){
					parms.userId=data.userId;
				}
				parms.account=$('#account').val();
				parms.password=$('#password').val();
				parms.userName=$('#names').val();
				parms.role=$('#userTypes').val();
				parms.phone=$('#phone').val();
				//parms.gender=$('#userSex').val();
				parms.status=currentStatus;
				if($('#userTypes').val()!=1){
					parms.townId=$('#userTown').val();
				}
				let nodes = [];
				if($('#childPut').attr('nodes')!=''){
					let checkedNodes = JSON.parse($('#childPut').attr('nodes'))
					$.each(checkedNodes,function(index, el) {
						nodes.push(el.id)
					});
				}
				parms.villageId=nodes;
				Ajax("/xjrest/user/user_save",saveBack,parms);
			});
		}
	}

	function saveBack(data){
		if(data.ret.success){
			layer.msg('保存成功');
		}else{
			layer.msg('保存失败!'+data.ret.message);
		}
		$('#closeInfo').click();
		reloadTable();
	}

	function reloadTable(){
		currentPage=1;
		setTable(0,5);
	}

	function setTable(from,count,parms){
		$('#gridRepairTable').datagrid({
	        url: '/xjrest/user/user_list?from='+from+'&count='+count,
	        queryParams:parms?parms:{},
	        width: '100%',
	        method: 'get',
	        border: false,
	        //showHeader:false,
	        singleSelect: true,
	        fitColumns:true,
	        scrollbarSize :0,
	        loadMsg: "正在查询,请耐心等待。。。。。。。",
	        columns: [
	            [
	            	{ field: 'account', title: '账号', width: "12%", height: "48px",align: 'center'},
	                { field: 'userName', title: '用户名', width: "12%", height: "48px",align: 'center'},
	                { field: 'town', title: '管辖街道', width: "15%", align: 'center',formatter: function(value,row){
	                	let str = '';
	                	$.each(value,function(index, el) {
	                		str+=el.townName+','
	                	});
	                	str=str.substring(0, str.length-1)
	                	return `<span title="${str}">${truncate(str,10)}</span>`;
	                }},
	                { field: 'village', title: '管辖社区', width: "12%", align: 'center' ,formatter: function(value,row){
	                	let str = '';
	                	$.each(value,function(index, el) {
	                		str+=el.villageName+','
	                	});
	                	str=str.substring(0, str.length-1)
	                	return `<span title="${str}">${truncate(str,10)}</span>`;
	                }},
	                { field: 'role', title: '角色', width: "12%", align: 'center',formatter: function(value,row){
	                	if(value == 1){
	                		return '系统管理员'
	                	}else if (value == 2) {
	                		return '街道管理员'
	                	}else if (value == 3) {
	                		return '巡检员'
	                	}else if (value == 4) {
	                		return '工作人员'
	                	}else if (value == 5) {
	                		return '普通用户'
	                	}
	                }},
	                { field: 'phone', title: '电话', width: "12%", align: 'center'},
	                /*{ field: 'gender', title: '性别', width: "6%", align: 'center',formatter: function(value,row){
	                	return value==1?'男':'女';
	                }},*/
	                { field: 'status', title: '状态', width: "10%", align: 'center',formatter: function(value,row){
	                	if(value==3){
	                		return `<div style="display:flex;justify-content: center;align-items: center;">
		                				<img src="./img/user/6EC7E26F-51D4-438C-8F14-3A29B5C0F84A@3x.png" style="width:.1rem;margin-right:9px" />
		                				<span>禁用</span>
	                				</div>`
	                	}else if (value==2) {
	                		return `<div style="display:flex;justify-content: center;align-items: center;">
		                				<img src="./img/user/840BD581-808F-4159-9EF9-7D51834EEA10@3x.png" style="width:.1rem;margin-right:9px" />
		                				<span>启用</span>
	                				</div>`
	                	}
	                }},
	                { field: 'userId', title: '操作', width: "15%", align: 'center',formatter: function(value,row){
	                		let data = JSON.stringify(row).replace(/\"/g,"'");
	                		let id = row.userId;
		                	return `<div style="display:flex;justify-content: center;align-items: center;">
		                				<input class="userTableButton buttonBlue" type="button" value="修改" style="margin-right:10px" onclick="showInfo(${data},'update')" />
			                			<input class="userTableButton buttonBlue" type="button" value="删除" onclick="delUser('${id}')" />
				                	</div>`
		                } 
	            	},
	            ]
	        ],
	        loadFilter: function(data){
	            let _data = data.ret.value;
	            let totals = data.ret.total;
	            if (totals == 0) {
	                $("#noRecordMessage").show();
	            } else {
	                $("#noRecordMessage").hide();
	            }
	            if (0 == totals % 5) {
	                totalPage = parseInt(totals / 5);
	                if (totalPage == 0){
	                     totalPage = 1;
	                }
	            } else {
	                totalPage = parseInt(totals / 5) + 1;
	            }
	            $('#pagination').paginations({
	                currentPage: currentPage,
	                totalPage: totalPage,
	                callback: function(current) {
	                    currentPage = current;
	                    current = (current - 1) * 5;
	                    setTable(current,5,parms);
	                }
	            });
	            return _data;
	        },
	        onDblClickRow: function(rowIndex, rowData) {
	        	showInfo(rowData,'show')
	        }
	    });
	}

	window.delUser=function(id){
		layer.confirm('确定删除该用户？', {
		  btn: ['确定','取消'] //按钮
		}, function(){
			Ajax("/xjrest/user/user_delete?userId="+id,delBack);
			layer.closeAll();
		}, function(){

		});
	}

	function delBack(data){
		if(data.ret.success){
			layer.msg('删除成功');
		}else{
			layer.msg('删除失败');
		}
		reloadTable();
	}

	return _user;
	
})

